package cn.wk.pay.controller;

import cn.wk.basic.config.AlipayConfig;
import cn.wk.pay.domain.AlipayInfo;
import cn.wk.pay.service.IAlipayInfoService;
import cn.wk.pay.service.IPayBillService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IPayBillService payBillService;

    /**
     * 异步请求要更改状态
     * @param request
     * @return
     */
    @RequestMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request) {
        try {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            //通过appid获取alipayinfo对象
            String app_id = params.get("app_id");
            AlipayInfo alipayInfo = alipayInfoService.findByAppId(app_id);

            boolean signVerified = false; //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);
            if (signVerified) {//验证成功
                //商户订单号
                String out_trade_no = request.getParameter("out_trade_no");
                //支付宝交易号
                String trade_no = request.getParameter("trade_no");
                //交易状态
                String trade_status = request.getParameter("trade_status");

                //成功的话就去更改状态并向支付宝返回success
                if (trade_status.equals("TRADE_SUCCESS")) {
                    payBillService.handleState(out_trade_no,trade_no);
                    return "success";
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //失败向支付宝返回fail
        return "failure";
    }

    /**
     * 同步请求要去跳转
     *
     * @param request
     * @return
     */
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request) {
        try {
            //获取支付宝GET过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            //通过appid获取alipayinfo对象
            String app_id = params.get("app_id");
            AlipayInfo alipayInfo = alipayInfoService.findByAppId(app_id);
            boolean signVerified = false; //调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type);
            //验签
            if (signVerified) {
                //验签成功的话跳转到成功页面
                return "redirect:http://localhost:8082/success.html";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //这里是失败，跳转到失败页面
        return "redirecr:http://localhost:8082/error.html";
    }
}
